package com.glodon.paas.document.storage.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glodon.paas.document.storage.Storage;
import com.glodon.paas.document.storage.StoreException;
import com.glodon.paas.document.storage.service.StorageService;
import com.glodon.paas.document.storage.util.JsonUtil;

@SuppressWarnings({ "unchecked", "rawtypes" })
@Controller
public class StorageController {
    @Autowired
    private StorageService storageService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public void list(Map model) {
        List<Storage> storages = storageService.getStorages();
        List<String> storageNames = new ArrayList<String>();
        for (Storage storage : storages) {
            storageNames.add(storage.getName());
        }
        model.put("storage", storageNames);
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void create(@RequestBody String json, Map model) throws IOException, StoreException {
        Map<String, String> params = JsonUtil.jsonToMap(json);
        storageService.createStorage(params.get("name"), params.get("directory"));
    }
}
